import 'package:flutter/material.dart';

///使用Animation给CustomPaint做动画，不推荐
class WaterPipeAnimation extends StatefulWidget {
  final Duration duration;

  const WaterPipeAnimation({
    Key? key,
    this.duration = const Duration(seconds: 2),
  }) : super(key: key);

  @override
  WaterPipeAnimationState createState() => WaterPipeAnimationState();
}

class WaterPipeAnimationState extends State<WaterPipeAnimation> with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  double value = 0;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      duration: widget.duration,
      vsync: this,
    );
    _controller.repeat(); // 使动画重复
    _controller.addListener(() {
      setState(() {
        value = _controller.value;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return CustomPaint(
      painter: WaterPipePainter(
        value,
      ),
      size: const Size(300, 500), // 或者根据父widget的大小来设置
    );
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }
}

class WaterPipePainter extends CustomPainter {
  double animation;

  WaterPipePainter(
    this.animation,
  ) {
    debugPrint('WaterPipePainter ===== }');
  }

  @override
  void paint(Canvas canvas, Size size) {
    canvas.drawRect(
      Rect.fromLTWH(0, 0, size.width, size.height),
      Paint()
        ..color = Colors.green
        ..style = PaintingStyle.fill,
    );
    Paint paint = Paint()
      ..color = const Color.fromRGBO(181, 181, 181, 1)
      ..strokeWidth = 5.0
      ..style = PaintingStyle.stroke
      ..isAntiAlias = true;
    double offsetX = animation * size.width;
    Path path = Path();
    path.moveTo(offsetX + 0.0, 48.0);
    path.lineTo(offsetX + 93.0, 50.0);
    path.lineTo(offsetX + 92.0, 115.0);
    path.lineTo(offsetX + 132.0, 116.0);
    path.lineTo(offsetX + 147.0, 93.0);
    path.lineTo(offsetX + 184.0, 107.0);
    path.lineTo(offsetX + 202.0, 93.0);
    path.lineTo(offsetX + 202.0, 53.0);
    path.lineTo(offsetX + 164.0, 53.0);
    path.lineTo(offsetX + 164.0, 12.0);
    path.lineTo(offsetX + 184.0, 12.0);
    path.moveTo(offsetX + 0.0, 50.0);
    path.moveTo(offsetX + 4.0, 50.0);
    path.lineTo(offsetX + 4.0, 180.0);
    path.lineTo(offsetX + 230.0, 180.0);
    path.moveTo(offsetX + 0.0, 50.0);
    path.moveTo(offsetX + 202.0, 180.0);
    path.lineTo(offsetX + 202.0, 100.0);
    path.moveTo(offsetX + 202.0, 180.0);
    path.close();
    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(WaterPipePainter oldDelegate) {
    debugPrint('WaterPipePainter shouldRepaint == ${this != oldDelegate}');
    return oldDelegate != this;
  }
}
